using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using PT.Common;

namespace PT.BLL;

/// <summary>
/// ModelScope API
/// </summary>
public static class ModelScopeQwenImage
{
    private static readonly string ApiKey = GetApiKey(); // 您的ModelScope Token
    private static readonly string ModelId = "Qwen/Qwen-Image"; //Qwen/Qwen-Image
    private static readonly string ApiUrl = "https://api-inference.modelscope.cn/"; // ModelScope API端点
    private static readonly HttpClient _httpClient = new HttpClient();

    private static string GetApiKey()
    {
        try
        {
            return getHostConfig.ModelScopeApiKey;
        }
        catch
        {
            // 出现异常时返回默认值
            return "";
        }
    }

    static ModelScopeQwenImage()
    {
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {ApiKey}");
        _httpClient.DefaultRequestHeaders.Add("X-ModelScope-Task-Type", "image_generation");
    }

    /// <summary>
    /// 轮询任务状态直到完成或失败
    /// </summary>
    /// <param name="taskId">任务ID</param>
    /// <returns>生成的图像URL</returns>
    public static async Task<string> PollTaskStatusUntilCompleteAsync(string taskId)
    {
        int maxAttempts = 60; // 最大尝试次数（5分钟）
        int attempt = 0;

        while (attempt < maxAttempts)
        {
            attempt++;

            // 创建查询任务状态的请求
            var request = new HttpRequestMessage(HttpMethod.Get, $"{ApiUrl}v1/tasks/{taskId}");

            // 发送请求
            HttpResponseMessage response = await _httpClient.SendAsync(request);
            response.EnsureSuccessStatusCode();

            // 解析响应
            using JsonDocument doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
            JsonElement data = doc.RootElement;

            string status = data.GetProperty("task_status").GetString();

            switch (status)
            {
                case "SUCCEED":
                    // 获取第一个输出图像的URL
                    var images = data.GetProperty("output_images");
                    if (images.GetArrayLength() > 0)
                    {
                        return images[0].GetString();
                    }
                    return null;

                case "FAILED":
                    Console.WriteLine("图像生成任务失败");
                    return null;

                case "CANCELED":
                    Console.WriteLine("图像生成任务被取消");
                    return null;

                default:
                    // 任务仍在处理中，等待5秒后再次检查
                    await Task.Delay(5000);
                    break;
            }
        }

        throw new TimeoutException("图像生成超时，5分钟内未完成");
    }



    /// <summary>
    /// 启动图像生成任务
    /// </summary>
    /// <param name="prompt">图像描述文本</param>
    /// <returns>任务ID</returns>
    public static async Task<string> StartImageGenerationAsync(string prompt)
    {
        // 构建请求数据
        var requestData = new
        {
            model = "Qwen/Qwen-Image",
            prompt = prompt,
            size = "1664x928"
        };

        // 序列化为JSON
        string jsonContent = JsonSerializer.Serialize(requestData);
        var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

        // 添加异步模式头
        content.Headers.Add("X-ModelScope-Async-Mode", "true");

        // 发送POST请求
        HttpResponseMessage response = await _httpClient.PostAsync($"{ApiUrl}v1/images/generations", content);
        response.EnsureSuccessStatusCode();

        // 解析响应获取任务ID
        using JsonDocument doc = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync());
        return doc.RootElement.GetProperty("task_id").GetString();
    }



    /// <summary>
    /// 根据文本描述生成图像并返回图像URL
    /// </summary>
    /// <param name="prompt">图像描述文本</param>
    /// <returns>生成的图像URL</returns>
    /// <exception cref="ArgumentException">当输入参数无效时抛出</exception>
    /// <exception cref="HttpRequestException">当网络请求失败时抛出</exception>
    /// <exception cref="TimeoutException">当操作超时时抛出</exception>
    public static async Task<string> GenerateImageAsync(string prompt)
    {
        // 参数验证
        if (string.IsNullOrWhiteSpace(prompt))
        {
            throw new ArgumentException("提示文本不能为空或空白字符串", nameof(prompt));
        }

        try
        {
            // 1. 发起异步图像生成请求
            string taskId = await StartImageGenerationAsync(prompt);

            if (string.IsNullOrEmpty(taskId))
            {
                throw new Exception("启动图像生成任务失败，未获取到任务ID");
            }

            // 2. 轮询任务状态直到完成
            string imageUrl = await PollTaskStatusUntilCompleteAsync(taskId);

            if (string.IsNullOrEmpty(imageUrl))
            {
                throw new Exception("图像生成失败或任务被取消");
            }

            return imageUrl;
        }
        catch (Exception ex)
        {
            // 记录错误日志（在实际应用中可以使用日志框架）
            Console.WriteLine($"生成图像时发生错误: {ex.Message}");
            throw; // 重新抛出异常
        }
    }
        


        















    

    
}


